package com.yxq.mdt.app.modules.socialcontact.ui.fragment.main;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.model.ShareBean;
import com.yxq.mdt.app.modules.bottomsheet.ShareSheetDialog;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.socialcontact.adapter.MainSocialContactVideoAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.MainSocialContactRecommendBean;
import com.yxq.mdt.app.modules.socialcontact.bean.VideoTopicBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialVideoContract;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialVideoPresenter;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.CircleTheHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialPersonalHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialStateDetailsAc;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.MediaPlayerHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.jzvd.Jzvd;

/**
 * 社区视频
 */
public class VideoFragment extends BaseFragment<MainSocialVideoPresenter> implements MainSocialVideoContract.View {
    public static final String EXTRA_TEXT = "extra_text";
    @BindView(R.id.social_state_recyclerView)
    RecyclerView socialStateRecyclerView;
    MainSocialContactVideoAdapter mainSocialContactAdapter;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<VideoTopicBean.ListBean> videoTopicBeans;
    private String userId;
    MyPersonalBean myPersonalBean;

    @Override
    protected int attachLayoutId() {
        setImmersionBarEnabled(false);
        return R.layout.fragment_social_video;
    }

    @Override
    protected MainSocialVideoPresenter getPresenter() {
        return new MainSocialVideoPresenter(this, new MainSocialContactModel());
    }

    @Override
    public void initView(View view) {
        myPersonalBean = Hawk.get(SPKey.SP_KEY_USER_MY_INFO, myPersonalBean);
        userId = String.valueOf(myPersonalBean.getUserId());
        videoTopicBeans = new ArrayList<>();
        socialStateRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mainSocialContactAdapter = new MainSocialContactVideoAdapter(R.layout.item_layout_dynamic_list, videoTopicBeans);
        socialStateRecyclerView.setAdapter(mainSocialContactAdapter);
        socialStateRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {
            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                try {
                    Jzvd jzvd = view.findViewById(R.id.item_social_video_player);
                    if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                        if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                            Jzvd.releaseAllVideos();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        socialStateRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mainSocialContactAdapter.countDownTimer != null) {
                    mainSocialContactAdapter.countDownTimer.onFinish();
                    MediaPlayerHelper.pause();
                }

            }
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getVideoTopic(page, 20, userId);
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mPresenter.getVideoTopic(page, 20, userId);
        });
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableAutoLoadMore(true);
    }

    @Override
    public void initData() {
        page = 1;
        mPresenter.getVideoTopic(page, 20, userId);
    }

    public void refresh() {
        page = 1;
        mPresenter.getVideoTopic(page, 20, userId);
    }

    @Override
    public void setData(@Nullable Object data) {

    }


    @Override
    public void onPause() {
        super.onPause();
        if (mainSocialContactAdapter.countDownTimer != null) {
            mainSocialContactAdapter.countDownTimer.cancel();
        }
        Jzvd.goOnPlayOnPause();
        MediaPlayerHelper.realese();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mainSocialContactAdapter.countDownTimer != null) {
            mainSocialContactAdapter.countDownTimer.cancel();
        }
        Jzvd.releaseAllVideos();
        MediaPlayerHelper.realese();
    }

    @Override
    public void onLoadVideoTopicTopicSuccess(VideoTopicBean videoTopicBean) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (page == 1) {
            mainSocialContactAdapter.setNewData(videoTopicBean.getList());
        } else {
            if (videoTopicBean.getList() != null && videoTopicBean.getList().size() != 0) {
                mainSocialContactAdapter.addData(videoTopicBean.getList());
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
        mainSocialContactAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.item_layout_nike_img:
                    if (mainSocialContactAdapter.countDownTimer != null) {
                        mainSocialContactAdapter.countDownTimer.onFinish();
                    }
                    Jzvd.releaseAllVideos();
                    MediaPlayerHelper.realese();
                    Intent it = new Intent(mContext, SocialPersonalHomepageAc.class);
                    it.putExtra("userId", mainSocialContactAdapter.getItem(position).getCreateMan());
                    startActivity(it);
                    break;
                case R.id.item_layout_content_browse:
                case R.id.item_layout_content_browse_img:
                case R.id.item_layout_content_browse_lint:
                    int giveNum = mainSocialContactAdapter.getItem(position).getUpCount();
                    if (mainSocialContactAdapter.getItem(position).getGiveLike() != 0) {
                        MainSocialContactModel.delGsTopicFavour("2", mainSocialContactAdapter.getItem(position).getId(), new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                mainSocialContactAdapter.getItem(position).setGiveLike(0);
                                mainSocialContactAdapter.getItem(position).setUpCount(giveNum - 1);
                                mainSocialContactAdapter.notifyDataSetChanged();
                                showCenterToast("取消点赞成功");
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("取消点赞失败");
                            }
                        });
                    } else {
                        MainSocialContactModel.saveGsTopicFavour(mainSocialContactAdapter.getItem(position).getId(), "2", new ApiModel.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String s) {
                                mainSocialContactAdapter.getItem(position).setGiveLike(1);
                                mainSocialContactAdapter.getItem(position).setUpCount(giveNum + 1);
                                mainSocialContactAdapter.notifyDataSetChanged();
                                showCenterToast("点赞成功");
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("点赞失败");
                            }
                        });
                    }
                    break;
                case R.id.item_layout_attention:
                    TextView attention = view.findViewById(R.id.item_layout_attention);
                    MainSocialContactModel.setInterestRelation(mainSocialContactAdapter.getItem(position).getUserId() + "", 1, 1, new ApiModel.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            for (VideoTopicBean.ListBean listBean : mainSocialContactAdapter.getData()) {
                                if (listBean.getUserId() == mainSocialContactAdapter.getItem(position).getUserId()) {
                                    listBean.setRelationNum(1);
                                    mainSocialContactAdapter.notifyDataSetChanged();
                                }
                            }
                            attention.setVisibility(View.GONE);
                            showCenterToast("关注成功");
                        }

                        @Override
                        public void onError(String errMsg) {
                            showCenterToast("关注失败");
                        }
                    });
                    break;
                case R.id.group_lint:
                    if (mainSocialContactAdapter.countDownTimer != null) {
                        mainSocialContactAdapter.countDownTimer.onFinish();
                    }
                    Jzvd.releaseAllVideos();
                    MediaPlayerHelper.realese();
                    Intent intent = new Intent(mContext, CircleTheHomepageAc.class);
                    intent.putExtra("id", mainSocialContactAdapter.getItem(position).getGroupId());
                    intent.putExtra("CircleName", mainSocialContactAdapter.getItem(position).getGsName());
                    startActivity(intent);
                    break;
                case R.id.item_layout_content_share:
                    //分享
                    ShareBean shareBean = new ShareBean();
                    if (!TextUtils.isEmpty(mainSocialContactAdapter.getItem(position).getContent())) {
                        shareBean.setTitle(mainSocialContactAdapter.getItem(position).getContent());//文本
                        shareBean.setText(mainSocialContactAdapter.getItem(position).getContent());//文本
                    } else {
                        shareBean.setTitle("社交电商新玩法，好玩让你意想不到。");//文本
                        shareBean.setText("社交电商新玩法，好玩让你意想不到。");//文本
                    }
                    shareBean.setShareType("0");//图文分享
                    shareBean.setShareTypeAPP(2);
                    shareBean.setHandleId(mainSocialContactAdapter.getItem(position).getId());
                    if (mainSocialContactAdapter.getItem(position).getFileList() != null && mainSocialContactAdapter.getItem(position).getFileList().size() > 0 && "1".equals(mainSocialContactAdapter.getItem(position).getFileList().get(0).getClass1())) {
                        shareBean.setImageUrl(mainSocialContactAdapter.getItem(position).getFileList().get(0).getFile());//LOGO
                    } else {
                        shareBean.setImageUrl("https://yxqoss.oss-cn-hangzhou.aliyuncs.com/gs_app/init/727c432c9e186a11.png");//LOGO
                    }
                    if (!"release".equals(BuildConfig.RELEASE)) {
                        shareBean.setUrl("http://testpm.quai69.com/webtrends.html?topicId=" + mainSocialContactAdapter.getItem(position).getId() + "&platform=2&parent_id=" + getParentId());//分享URL
                    } else {
                        shareBean.setUrl("http://pm.quai69.com/webtrends.html?topicId=" + mainSocialContactAdapter.getItem(position).getId() + "&platform=2&parent_id=" + getParentId());
                    }
                    ShareSheetDialog shareSheetDialog = new ShareSheetDialog(shareBean, false);
                    shareSheetDialog.show(getChildFragmentManager(), "shareSheetDialog");
                    break;
            }
        });
        mainSocialContactAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (mainSocialContactAdapter.countDownTimer != null) {
                mainSocialContactAdapter.countDownTimer.cancel();
            }
            Jzvd.releaseAllVideos();
            MediaPlayerHelper.realese();
            Intent it = new Intent(mContext, SocialStateDetailsAc.class);
            it.putExtra("topicId", mainSocialContactAdapter.getItem(position).getId());
            it.putExtra("id", mainSocialContactAdapter.getItem(position).getId());
            startActivity(it);
        });

    }

    @Override
    public void onLoadVideoTopicTopicFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

}
